package com.yzxb.messystem.controller;

import com.yzxb.messystem.entity.WorkOrder;
import com.yzxb.messystem.exception.ResourceNotFoundException;
import com.yzxb.messystem.exception.BusinessException;
import com.yzxb.messystem.service.WorkOrderService;
import com.yzxb.messystem.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/workorders")
public class WorkOrderController {
    
    @Autowired
    private WorkOrderService workOrderService;
    
    // 获取所有工单
    @GetMapping
    public ResponseResult<List<WorkOrder>> getAllWorkOrders() {
        List<WorkOrder> workOrders = workOrderService.getAllWorkOrders();
        return ResponseResult.success("获取工单列表成功", workOrders);
    }
    
    // 根据ID获取工单
    @GetMapping("/{id}")
    public ResponseResult<WorkOrder> getWorkOrderById(@PathVariable Long id) {
        try {
            WorkOrder workOrder = workOrderService.getWorkOrderById(id)
                    .orElseThrow(() -> new ResourceNotFoundException("工单不存在，ID: " + id));
            return ResponseResult.success("获取工单成功", workOrder);
        } catch (ResourceNotFoundException e) {
            return ResponseResult.error(404, e.getMessage());
        }
    }
    
    // 根据工单编码获取工单
    @GetMapping("/code/{orderCode}")
    public ResponseResult<WorkOrder> getWorkOrderByCode(@PathVariable String orderCode) {
        try {
            WorkOrder workOrder = workOrderService.getWorkOrderByCode(orderCode)
                    .orElseThrow(() -> new ResourceNotFoundException("工单不存在，编码: " + orderCode));
            return ResponseResult.success("获取工单成功", workOrder);
        } catch (ResourceNotFoundException e) {
            return ResponseResult.error(404, e.getMessage());
        }
    }
    
    // 添加工单
    @PostMapping
    public ResponseResult<WorkOrder> addWorkOrder(@RequestBody WorkOrder workOrder) {
        try {
            WorkOrder newWorkOrder = workOrderService.addWorkOrder(workOrder);
            return ResponseResult.success("添加工单成功", newWorkOrder);
        } catch (RuntimeException e) {
            return ResponseResult.error(400, "添加工单失败: " + e.getMessage());
        }
    }
    
    // 更新工单
    @PutMapping("/{id}")
    public ResponseResult<WorkOrder> updateWorkOrder(@PathVariable Long id, @RequestBody WorkOrder workOrder) {
        try {
            workOrder.setId(id);
            WorkOrder updatedWorkOrder = workOrderService.updateWorkOrder(id, workOrder);
            return ResponseResult.success("更新工单成功", updatedWorkOrder);
        } catch (RuntimeException e) {
            return ResponseResult.error(404, "更新工单失败: " + e.getMessage());
        }
    }
    
    // 删除工单
    @DeleteMapping("/{id}")
    public ResponseResult<Void> deleteWorkOrder(@PathVariable Long id) {
        try {
            workOrderService.deleteWorkOrder(id);
            return ResponseResult.success("删除工单成功", null);
        } catch (RuntimeException e) {
            return ResponseResult.error(404, "删除工单失败: " + e.getMessage());
        }
    }
    
    // 根据状态查询工单
    @GetMapping("/status/{status}")
    public ResponseResult<List<WorkOrder>> getWorkOrdersByStatus(@PathVariable WorkOrder.OrderStatus status) {
        List<WorkOrder> workOrders = workOrderService.getWorkOrdersByStatus(status);
        return ResponseResult.success("按状态查询工单成功", workOrders);
    }
    
    // 根据产品线查询工单
    @GetMapping("/line/{productionLine}")
    public ResponseResult<List<WorkOrder>> getWorkOrdersByProductionLine(@PathVariable String productionLine) {
        List<WorkOrder> workOrders = workOrderService.getWorkOrdersByProductionLine(productionLine);
        return ResponseResult.success("按产品线查询工单成功", workOrders);
    }
    
    // 根据产品ID查询工单
    @GetMapping("/product/{productId}")
    public ResponseResult<List<WorkOrder>> getWorkOrdersByProductId(@PathVariable Long productId) {
        List<WorkOrder> workOrders = workOrderService.getWorkOrdersByProductId(productId);
        return ResponseResult.success("按产品ID查询工单成功", workOrders);
    }
    
    // 根据日期范围查询工单
    @GetMapping("/date-range")
    public ResponseResult<List<WorkOrder>> getWorkOrdersByDateRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endDate) {
        List<WorkOrder> workOrders = workOrderService.getWorkOrdersByDateRange(startDate, endDate);
        return ResponseResult.success("按日期范围查询工单成功", workOrders);
    }
    
    // 更改工单状态
    @PutMapping("/{id}/status/{status}")
    public ResponseResult<WorkOrder> changeWorkOrderStatus(@PathVariable Long id, @PathVariable WorkOrder.OrderStatus status) {
        try {
            WorkOrder updatedWorkOrder = workOrderService.changeWorkOrderStatus(id, status);
            return ResponseResult.success("更改工单状态成功", updatedWorkOrder);
        } catch (RuntimeException e) {
            return ResponseResult.error(404, "更改工单状态失败: " + e.getMessage());
        }
    }
    
    // 更新工单数量
    @PutMapping("/{id}/quantities")
    public ResponseResult<WorkOrder> updateWorkOrderQuantities(
            @PathVariable Long id,
            @RequestParam(required = false) Integer completedQuantity,
            @RequestParam(required = false) Integer rejectedQuantity) {
        try {
            WorkOrder updatedWorkOrder = workOrderService.updateWorkOrderQuantities(id, completedQuantity, rejectedQuantity);
            return ResponseResult.success("更新工单数量成功", updatedWorkOrder);
        } catch (RuntimeException e) {
            return ResponseResult.error(404, "更新工单数量失败: " + e.getMessage());
        }
    }
}